package com.qifei.xmlg_backend.aspect;

import com.qifei.xmlg_backend.service.ILogsService;
import com.qifei.xmlg_backend.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

@Aspect
@Component
public class OperationLogAspect {

    @Autowired
    private ILogsService logService;

    @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping) || " +
            "@annotation(org.springframework.web.bind.annotation.PostMapping) || " +
            "@annotation(org.springframework.web.bind.annotation.PutMapping) || " +
            "@annotation(org.springframework.web.bind.annotation.DeleteMapping)")
    public void operationLogPointcut() {}

    @Around("operationLogPointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取请求信息
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();

        // 获取操作名称（简单使用URL作为操作名）
        String operation = request.getRequestURI();
        String method = request.getMethod();
        String ip = getClientIp(request);
        String token = request.getHeader("token");
        Object result = joinPoint.proceed();
        if (StringUtils.hasLength(token)){
            Claims claims = JwtUtils.parseJWT(token);
            if (claims != null) {
                Long userId = Long.valueOf(claims.get("id").toString());
                String username = claims.get("username").toString();
                // 记录操作日志
                logService.recordLog(userId, username, operation, method,
                        request.getRequestURI(), ip, 1);
            } else {
                logService.recordLog(null, "Unknown", operation, method,
                        request.getRequestURI(), ip, 0);
            }
        }else{
            logService.recordLog(null, "Unknown", operation, method,
                    request.getRequestURI(), ip, 0);
        }
        return result;
    }

    private String getClientIp(HttpServletRequest request) {
        // 实现获取客户端IP的逻辑
        return request.getRemoteAddr();
    }
}
